package com.king.tv.mvp.fragment;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.king.base.adapter.ViewPagerFragmentAdapter;
import com.king.base.util.ToastUtils;
import com.king.tv.App;
import com.king.tv.Constants;
import com.king.tv.MainActivity;
import com.king.tv.R;
import com.king.tv.bean.LiveCategory;
import com.king.tv.bean.LiveImageList;
import com.king.tv.bean.MovieMenu;
import com.king.tv.bean.NoticeInfo;
import com.king.tv.bean.Video;
import com.king.tv.http.ApiConfig;
import com.king.tv.http.BaseCallModel;
import com.king.tv.http.HttpLoader;
import com.king.tv.mvp.base.BaseFragment;
import com.king.tv.mvp.presenter.CategoryPresenter;
import com.king.tv.mvp.view.ICategoryView;
import com.king.tv.util.SPUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.bingoogolapple.bgabanner.BGALocalImageSize;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author Jenly <a href="mailto:jenly1314@gmail.com">Jenly</a>
 * @since 2017/2/20
 */

public class HomeFragment extends BaseFragment<ICategoryView, CategoryPresenter> implements ICategoryView {

    @BindView(R.id.ivLeft)
    ImageView ivLeft;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.btnMore)
    ImageView btnMore;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    @BindView(R.id.banner_home)
    cn.bingoogolapple.bgabanner.BGABanner banner;

    private ViewPagerFragmentAdapter viewPagerFragmentAdapter;

    private List<LiveCategory> listCategory;

    private List<CharSequence> listTitle;

    private List<Fragment> listData;

    private List<MovieMenu> menuList;
    public static HomeFragment newInstance() {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getRootViewId() {
        return R.layout.fragment_home;
    }

    /**
     * 初始化数据
     */
    @Override
    public void initUI() {
        listCategory = new ArrayList<>();
        listTitle = new ArrayList<>();
        listData = new ArrayList<>();
        initTab();
        String Userid = SPUtils.getString(getActivity(),"userid","");
        if(Userid!=null){
        HttpLoader httpLoader = new HttpLoader();
        httpLoader.getMovieMenu().subscribe(new Observer<BaseCallModel<List<MovieMenu>>>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.i("tag","=========Result"+d.toString());
            }

            @Override
            public void onNext(BaseCallModel<List<MovieMenu>> list) {
                Log.i("tag","======List电影栏目的条数"+list.getData().size());
                getMovie(list.getData());
                menuList = list.getData();
                if(list.getData().size()>0){
//                    listTitle.add(getText(R.string.recommend));
//                    listData.add(RecommendFragment.newInstance());
//                    listTitle.add(getText(R.string.tab_all));
//                    listData.add(LiveListFragment.newInstance(null));
//                    listData.add(LiveListFragment.newInstance(null));
                    for(int i=0;i<list.getData().size();i++ ){
                        MovieMenu l = list.getData().get(i);
                        listTitle.add(l.getTitle());
                        listData.add(LiveListFragment.newInstance(l.getId()));
                    }
                    viewPagerFragmentAdapter = new ViewPagerFragmentAdapter(getChildFragmentManager(),listData,listTitle);

                    viewPager.setAdapter(viewPagerFragmentAdapter);
                    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                        @Override
                        public void onTabSelected(TabLayout.Tab tab) {
                            App.tabposition = tab.getPosition();
                            View view = tab.getCustomView();
                            if (null == view) {
                                tab.setCustomView(R.layout.tabtextlayout);
                            }
                            TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
                            textView.setTextColor(tabLayout.getTabTextColors());
                            textView.setTypeface(Typeface.DEFAULT_BOLD);
                        }

                        @Override
                        public void onTabUnselected(TabLayout.Tab tab) {
                            View view = tab.getCustomView();
                            if (null == view) {
                                tab.setCustomView(R.layout.tabtextlayout);
                            }
                            TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
                            textView.setTypeface(Typeface.DEFAULT);
                        }

                        @Override
                        public void onTabReselected(TabLayout.Tab tab) {

                        }
                    });
                    tabLayout.setupWithViewPager(viewPager);
                }

            }

            @Override
            public void onError(Throwable e) {
                Log.i("tag","=========Result"+e.toString());
            }

            @Override
            public void onComplete() {
                Log.i("tag","=========Result end");
            }
            });
        }
    }



    @Override
    public void initData(){
//        getPresenter().getAllCategoriesByDB();
        getPresenter().getAllCategories();
    }



    public void getMovie(List<MovieMenu> list){
        Log.i("tag","=========Result 请求电影蓝么");
        if(list!=null&&list.size()>0){
//            HttpLoader httpLoader = new HttpLoader();
//            httpLoader.getMovie(list.get(0).getId()).subscribe(new Observer<String>() {
//                @Override
//                public void onSubscribe(Disposable d) {
//                    Log.i("tag","=========Result"+d.toString());
//                }
//
//                @Override
//                public void onNext(String value) {
//                    Log.i("tag","=========Result"+value.toString());
//
//                }
//
//                @Override
//                public void onError(Throwable e) {
//                    Log.i("tag","=========Result"+e.toString());
//                }
//
//                @Override
//                public void onComplete() {
//                    Log.i("tag","=========Result end");
//                }
//            });
        }
    }

    @NonNull
    @Override
    public CategoryPresenter createPresenter() {
        return  new CategoryPresenter(getApp());
    }


    @Override
    public void onGetLiveCategory(List<LiveCategory> list) {


        if(list!=null){
            toSetList(listCategory,list,false);
            listData.clear();
            List<CharSequence> listTemp = new ArrayList<>();

            //----------------------
            listTemp.add(getText(R.string.recommend));
            listData.add(RecommendFragment.newInstance());
            listTemp.add("更多");
            listData.add(RecommendFragment.newInstance());
            listTemp.add(getText(R.string.tab_all));
            listData.add(LiveListFragment.newInstance(null));
            //----------------------
            for (int i = 0; i < list.size(); i++) {
                LiveCategory liveCategory = list.get(i);
                listTemp.add(liveCategory.getName());
                listData.add(LiveListFragment.newInstance(liveCategory.getSlug()));
            }
            toSetList(listTitle,listTemp,false);

        }

        if(viewPagerFragmentAdapter!=null){
            viewPagerFragmentAdapter.setListTitle(listTitle);
            viewPagerFragmentAdapter.setListData(listData);
            viewPagerFragmentAdapter.notifyDataSetChanged();
        }
    }

    public void updateLiveCategory(List<LiveCategory> list,boolean isFirst){

    }


    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void onCompleted() {

    }


    @OnClick({R.id.ivLeft, R.id.ivRight, R.id.btnMore,R.id.fab})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivLeft:
                startActivity(getFragmentIntent(Constants.SEARCH_FRAGMENT));
                break;
            case R.id.ivRight:
                startLogin();
                break;
            case R.id.btnMore:
                break;
            case R.id.fab:
                startAbout();
                break;

        }
    }

    private void initTab() {
        HttpLoader.getInstance().getLiveImage().subscribe(new Observer<BaseCallModel<Object>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseCallModel<Object> value) {
                Gson gson = new Gson();
                String json = gson.toJson(value);
                BaseCallModel baseCallModel = gson.fromJson(json,BaseCallModel.class);
                if(baseCallModel!=null){
                    String json1 = gson.toJson(baseCallModel.getData());
                    final List<LiveImageList> liveImageLists = gson.fromJson(json1,new TypeToken<List<LiveImageList>>(){}.getType());
                    BGALocalImageSize localImageSize = new BGALocalImageSize(720, 230, 480, 200);
                    banner.setAdapter(new BGABanner.Adapter<LinearLayout, String>() {
                        @Override
                        public void fillBannerItem(BGABanner banner, LinearLayout itemView, String model, int position) {
                            ImageView simpleDraweeView = itemView.findViewById(R.id.iv_item_fresco);
                            Glide.with(getContext()).load(model).apply(RequestOptions.bitmapTransform(new RoundedCorners(10))).diskCacheStrategy(DiskCacheStrategy.RESOURCE).into(simpleDraweeView);
                        }
                    });
                    //设置数据源
                    List<String> list = new ArrayList<>();
                    for(LiveImageList e:liveImageLists){
                        list.add(ApiConfig.BASE_URL+e.getImg());
                    }
                    banner.setData(R.layout.item_fresco, list, null);
                    banner.setDelegate(new BGABanner.Delegate<LinearLayout, String>() {
                        @Override
                        public void onBannerItemClick(BGABanner banner, LinearLayout itemView, String model, int position) {
                            Log.i("tag","==============liveimage"+ liveImageLists.get(banner.getCurrentItem()).getUrl());
                            Log.i("tag","==============liveimage"+position);
                            if(liveImageLists.get(banner.getCurrentItem()).getUrl().startsWith("http")){
                                openBrowser(getActivity(),liveImageLists.get(banner.getCurrentItem()).getUrl());}
                        }
                    });
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.i("tag","=========Result 被选中了"+tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                Log.i("tag","=========Result 未被选中了");
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                Log.i("tag","=========Result 已经未被选中了");
            }
        });
    }

    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
//            LogUtil.d("suyan = " + componentName.getClassName());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
//            GlobalMethod.showToast(context, "链接错误或无浏览器");
        }
    }
}
